//
//  WBMainViewController.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/2/28.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import UIKit
import SVProgressHUD
//主控制器
class WBMainViewController: UITabBarController {

    //定时器
    fileprivate var timer : Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        
        setupTimer()
        
        //设置新特性视图
        setupNewFeatureViews()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        //销毁时钟
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    //portrait  竖屏  肖像
    //landscape 横屏  风景
    
    //设置当前控制器及子控制器都会遵循这个方向
    //如果播放视频 通常是通过model实现
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    //MARK: - 监听方法
    @objc private func userLogin(n:Notification){
        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        //判断n的object是否有值，如果有值，则提示用户重新登录
        if n.object != nil{
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            //修改延迟时间
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            //展现登录控制器   通常会跟uinavigationcontroller连用
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }
        
    }

    public lazy var composeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        
        // 会根据背景图片的大小调整尺寸
        button.sizeToFit()
        return button
    }()
    
    func composeStatus(){
        //let vc = UIViewController()
        //vc.view.backgroundColor = UIColor.red
        //present(vc, animated: true, completion: nil)
        print("撰写微博")
    }
}

extension WBMainViewController{
    fileprivate func setupNewFeatureViews(){
        //0. 判断是否登录
        if !WBNetworkManager.shared.userLogon{
            return
        }
        //1. 检查版本是否更新
        
        //2. 如果更新，显示新特性，否则显示欢迎
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        //3. 添加视图
        //v.frame = view.bounds
        
        view.addSubview(v)
    }
    
    /// 计算型属性  不会占用存储空间
    private var isNewVersion: Bool {
        //1. 取当前版本
        print(Bundle.main.infoDictionary ?? "")
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        print(currentVersion)

        //2. 取保存在document（ituns备份）目录中的之前版本号
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        print(sandboxVersion)
        print(path)
        
        //3. 将当前版本号保存在沙盒
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        //4. 比较两个版本是否一致
        return currentVersion != sandboxVersion
    }
}

//MARK: - UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate{
    
    
    /// 将要选择TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        //获取控制器在数组中的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        //判断当前在首页，点击首页
        if selectedIndex == 0 && index == selectedIndex{
            print("点击首页")
            //让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            //刷新数据
            //DispatchQueue.main.afer
            vc.loadData()
            
            //清除tabItem 的 badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        //判断目标控制器是否是 uiviewcontroller
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK : 时钟方法
extension WBMainViewController{
    fileprivate func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(updataTimer), userInfo: nil, repeats: true)
    }
    
    //时钟触发方法
    @objc private func updataTimer(){
        if !WBNetworkManager.shared.userLogon{
            return
        }
        //print(#function)
        WBNetworkManager.shared.unreadCount { (count) in
            //print("有\(count)条新微博")
            //设置首页tabbaritem badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置 app 图标的badgenumber  从ios8.0之后要用户授权之后才能够显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

//extension 类似于OC中的分类，在swift中还可以用来切分代码块
//可以把相近功能的函数，放在一个extension中
//便于代码维护
//注意：和OC的分类一样，extension中不能定义属性
//MARK:设置界面
extension WBMainViewController{
    //设置撰写按钮
    public func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮宽度
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        
        //CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: UIControlEvents.touchUpInside)
    }
    
    //设置所有子控制器
    //NSArray(contentsOfFile: path) 可以取plist中取数据 不能取json
    public func setupChildControllers(){
        
        //获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                         FileManager.SearchPathDomainMask.userDomainMask,
                                                         true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            //从bundle加载json
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        //try?  推荐  如果解析成功就有值，否则为nil
        //try!  不推荐  如果解析成功就有值，否则崩溃
        //处理异常
//        do{
//            let array = try JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]]
//            print(array ?? "")
//        }catch{
//            print(error)
//        }
        //从bundle加载配置的json
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]] else{
        //let array = NSArray(contentsOfFile: path) as? [[String:AnyObject]] else{
            return
        }
        
        //在现在很多应用程序，界面的创建都依赖网络 json
//        let array:[[String:Any]]=[
//            ["clsName":"WBHomeViewController","title":"首页","imageName":"tabbar_home",
//             "visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
//            ["clsName":"WBMessageViewController","title":"消息","imageName":"tabbar_message_center",
//             "visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            ["clsName":"UIViewController"],
//            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"tabbar_discover",
//             "visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
//            ["clsName":"WBProfileViewController","title":"我","imageName":"tabbar_profile",
//             "visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//        ]
        
        //测试数据格式是否正确
        //print((array as NSArray).write(toFile: "/Users/dingzhibing/Documents/2016/demo.plist", atomically: true))
        
        //数组-> json序列化
        //判断能不能转化
//        if(JSONSerialization.isValidJSONObject(array)){
//            let data = try? JSONSerialization.data(withJSONObject: array, options: [])
//            let fileURL = NSURL.fileURL(withPath: "/Users/dingzhibing/Documents/2016/demo.json")
//            
//            try? data?.write(to: fileURL)
//        }
        
        
        var arrayM = [UIViewController]()
        for dict in array!{
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
    //
    private func controller(dict:[String:AnyObject])->UIViewController{
        //取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace+"."+clsName) as? WBBaseViewController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String:String]
        else {
            return UIViewController()
        }
        
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        vc.visitorInfo = visitorInfo
        
        //设置tabbar图像
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName+"_highlighted")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        
        //设置tabbar的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: UIControlState.highlighted)
        //vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize:14.0)], for: UIControlState.normal)
        
        let nav = WBNavigationController(rootViewController:vc)
        return nav
    }
}
